<?php

namespace App\Kuafu\Export\Service\ExportFactory;

use App\Kuafu\Export\Model\ExportDownloadModel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Kuafu\CsvStream\Exporter;
use Kuafu\File\FileUtil;

abstract class BaseExportService
{
    protected ExportDownloadModel $exportDownloadModel;

    /**
     * $exportDownloadModel.params
     * @var array
     */
    protected array $params;

    protected function __construct(ExportDownloadModel $exportDownloadModel)
    {
        $this->exportDownloadModel = $exportDownloadModel;

        $this->params = $exportDownloadModel->params ? json_decode($exportDownloadModel->params, true) : [];
    }

    /**
     * 初始化，并获取对象
     * @param $params
     * @return static
     */
    public static function getIns(ExportDownloadModel $exportDownloadModel): self
    {
        return (new static($exportDownloadModel));
    }

    /**
     * 查询数据
     * @return self
     */
    abstract protected function query(): self;

    /**
     * 获取oss文件path
     * @return string
     */
    abstract protected function path(): string;

    /**
     * 写入&上传
     * @param string $content
     * @param string $fileName
     * @param string $fileSuffix
     * @return string
     * @throws \OSS\Core\OssException
     */
    protected function writeUpload(string $content, string $ext = ''): string
    {
        if (!$ext) {
            $ext = ExportDownloadModel::FILE_TYPE_EXT[$this->exportDownloadModel->fileType] ?? '';
        }

        $path = sys_get_temp_dir() . '/' . Str::random();
        $fd   = fopen($path, 'w+');

        fwrite($fd, $content);

        if (is_resource($fd)) {
            fclose($fd);
        }

       return $this->upload($path, $ext);
    }

    /**
     * 上传
     * @param string $path
     * @param string $fileSuffix
     * @return string
     * @throws \OSS\Core\OssException
     */
    protected function upload(string $path, string $ext = ''): string
    {
        if (!$ext) {
            $ext = ExportDownloadModel::FILE_TYPE_EXT[$this->exportDownloadModel->fileType] ?? '';
        }

        $fileName   = $this->exportDownloadModel->name;
        $objectName = "export/rms/" . date('Ymd') . "/" . Str::random() . "/{$fileName}.{$ext}";

        $path = FileUtil::uploadFile($path, $ext, $objectName)['path'];
        Log::info("writeUpload:{$path}:{$fileName}:{$ext}");

        return $path;
    }

    /**
     * 写入csv
     * @param array $header
     * @param array $content
     * @return string
     */
    protected function writeCsv(array $header, array $content): string
    {
        $path = sys_get_temp_dir() . '/' . Str::random();
        $exporter        = new Exporter('', true, $path);
        $exporter->setDie(false);
        $exporter->writeHeaders($header);

        foreach ($content as $line) {
            $exporter->writeLine($line);
        }

        return $path;
    }
}
